/*
 * AvailableNum.java
 *
 * Created on 2007 10:54
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package cn.tearcry.jsudoku;
import java.util.ArrayList;
import java.util.Iterator; 
import javax.swing.JButton;
/**
 *
 * @author 马建乐 */
public class AvailableNum {

    private  ArrayList <Integer> availableNum=new ArrayList <Integer>();
    private GridButton button;
    private GridButton[][] btnArry;
   
   
    /**
     * Creates a new instance of AvailableNum
     */
    public AvailableNum (GridButton button,GridButton[][] btnArry) {
        this.button=button;
        this.btnArry=btnArry;
        for(int i=1;i<10;i++) 
            availableNum.add (i);         
      
    }
    
    private void cutColumn() {              
        Iterator <Integer> iter;
        for(int i=0;i<btnArry.length;i++) {
           iter=availableNum.iterator ();
            while(iter.hasNext ()) {
                if(iter.next ().intValue ()==btnArry[i][button.getColumn ()].getNum ())
                    iter.remove ();
                
            }
        }
    }
    
    private void cutRow() {        
      Iterator <Integer> iter;
        for(int i=0;i<btnArry.length;i++) {
           iter=availableNum.iterator ();
            while(iter.hasNext ()) {
                if(iter.next ().intValue ()==btnArry[button.getRow ()][i].getNum ())
                    iter.remove ();
                
            }
        }
    }
    
    private void cutNeighbour() {
        int r=(int)button.getRow()/3;
        int c=(int)button.getColumn ()/3;
         Iterator <Integer> iter;
        for(int i=r*3;i<(r+1)*3;i++) {
            for(int j=c*3;j<(c+1)*3;j++) {
                iter=availableNum.iterator ();
                while(iter.hasNext ()) {  
                    if(iter.next ().intValue ()==btnArry[i][j].getNum ())
                    iter.remove ();                
                }
            }
                
        } 
    }
 
    
    public ArrayList <Integer> getAvailableNum() {
          int len=availableNum.size (); 
        //系统填写则返回null 
        if(button.isPuzzleFill ()) {
             return null;
             
        }
          if(button.isUserHasFill ()) {          
           for(int i=0;i<len;i++) 
               availableNum.remove (0);
           availableNum.add (Integer.valueOf(button.getNum()));
           return availableNum;
        }
        
        cutRow();
        cutColumn();
        cutNeighbour();
        return availableNum;
    }
}
